package com.example.android2019.ch3;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android2019.R;

public class Ch3SpActivity extends AppCompatActivity {
    Button btn_read, btn_write;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch3_sp);
        btn_read = findViewById(R.id.ch3_file_sp_btn_read);
        btn_write = findViewById(R.id.ch3_file_sp_btn_write);
        textView = findViewById(R.id.ch3_file_sp_tv);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                switch (v.getId()) {
                    case R.id.ch3_file_sp_btn_write:
                        write();
                        break;
                    case R.id.ch3_file_sp_btn_read:
                        read();
                        break;
                }
            }
        };
        btn_write.setOnClickListener(listener);
        btn_read.setOnClickListener(listener);

        /*获取传递的数据*/
        Intent intent = this.getIntent();
        String a = intent.getStringExtra("test");
        Toast.makeText(this, a, Toast.LENGTH_SHORT).show();
    }

    private void read() {
        SharedPreferences sp = this.getSharedPreferences("pty", MODE_PRIVATE);
        String name = sp.getString("name", null);
        int age = sp.getInt("age", 0);
        textView.setText(name + " " + age);
    }

    private void write() {
        SharedPreferences sp = this.getSharedPreferences("pyt", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("name", "zhangsan");
        editor.putInt("age", 20);
        editor.commit();
        Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
    }
    }

